<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="static/js/jquery.min.js"></script>
        <script type="text/javascript" src="static/js/cache.js"></script>
        <script type="text/javascript" src="static/js/facebook.js"></script>
        <script type="text/javascript" src="static/js/network.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <script type="text/javascript">
            /* Check interval */
            window.checkInterval = 45;
            
            /* Expose data cache, so popup can use it */
            window.data = {};
            
            /* Expose setCount */
            window.setCount = function(unread) {
                if(unread && unread > 0) {
                    chrome.browserAction.setBadgeText({text: '' + unread});
                } else {
                    chrome.browserAction.setBadgeText({text: ''});
                }
            };
            
            /* Mark a notification as read */
            window.markRead = function(id) {
                FB.api(id, 'POST', {unread: 0}, function() {
                    try {
                        updateFacebook();
                    } catch(e) {}
                });
            };
            
            /* Popout */
            (function() {
                var _pop;
                window.popout = function() {
                    if(_pop) {
                        _pop.focus();                    
                    } else {
                        _pop = window.open('popup.html', 'popout', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=470,height=480,dialog=yes');
                    }
                }
            })();
            
            /* Context Menu */
            chrome.contextMenus.removeAll();
            chrome.contextMenus.create({
                title: 'Share on Facebook',
                contexts: ["page", "link", "image"],
                onclick: function(obj) {
                    var link = false;
                    if(obj.mediaType && obj.mediaType == 'image') {
                        link = obj.srcUrl
                    } else if(obj.linkUrl) {
                        link = obj.linkUrl;
                    } else {
                        link = obj.pageUrl;
                    }
                    
                    if(link) {
                        FB.api('me/feed', 'POST', {link: link});
                    }
                }
            });
            
            /* Init FB with app id and permissions */
            Cache.set('deniedPermissions', 1);
            FB.init('216040718429530', 'offline_access,read_stream,publish_stream,read_mailbox,friends_birthday,user_checkins,friends_checkins,user_photos,friends_photos,publish_checkins,manage_notifications,user_groups');
            if(FB.getAccessToken()) {
                Cache.remove('deniedPermissions');
            }
            
            
            /* Update Facebook */
            var updateFacebook = function(updateFeed) {
                var calls = [{"method": "GET", "relative_url": "me/notifications"}];
                        
                /* Only update newsfeed if they say so */
                if(updateFeed) {
                    calls.push({"method": "GET", "relative_url": "me/home?limit=25"});
                }
                
                FB.api('', 'POST', {batch: JSON.stringify(calls)}, function(res) {
                    try {
                        var notifs = res[0],
                            posts = res[1] || false;
                        
                        /* Check for notifs */
                        if(notifs && notifs.body && !notifs.body.error) {
                            var body = JSON.parse(notifs.body);
                            // If we are over the request limit wait longer
                            if(body && body.error && body.error.code == 4) {
                                checkInterval = 200;
                                return;
                            }
                            checkInterval = 45;
                            
                            window.data.notifs = body;
                            var count = (window.data.notifs.data) ? window.data.notifs.data.length : 0;
                            if(count > 0) {
                                var encoded = encodeURIComponent(JSON.stringify(window.data.notifs.data[0]));
                                //webkitNotifications.createHTMLNotification( 'notification.html#' + encoded ).show();
                            }
                            setCount(count);
                        }
                        
                        /* Check for posts */
                        if(posts && posts.body && !posts.body.error) {
                            window.data.posts = JSON.parse(posts.body);
                        }
                    } catch(e) { }
                });
            };
            
            /* Loop */
            (function() {
                var timestamp = 0,
                    nfTimestamp = 0;
                
                setInterval(function() {
                    chrome.idle.queryState(15, function(state) {
                        /* Test for activity & online & fb session */
                        if(state != 'active' || !navigator.onLine || !FB.getAccessToken() || Cache.get('deniedPermissions')) { return; }
                        
                        /* If we checked in the last 45 seconds, wait */
                        var now = parseInt((new Date()).getTime() / 1000);
                        if(now - checkInterval < timestamp) { return; }
                        timestamp = now;
                        
                        /* Update Facebook Data */
                        var shouldUpdateFeed = (now - 600 >= nfTimestamp) ? true : false;
                        if(shouldUpdateFeed) {
                            nfTimestamp = now;
                        }
                        updateFacebook(shouldUpdateFeed);
                    });
                }, 1000);
            })();

            /* Get the user info when chrome boots */
            if(!Cache.get('deniedPermissions')) {
                FB.getUser();
            }
                
            /* Listen for messages from other app components */
    		chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
                if(request && request.type == 'auth') {
        	    	try {
        	    	    Cache.remove('deniedPermissions');
        	    	    var token = request.session.split("#").join("").split("&")[0].split("=")[1];
        	    	    if(!token || !('session' in request) || (request.session && request.session == "#_=_")) {
        	    	        sendResponse({});
        	    	        throw(0);
        	    	        return;
        	    	    }
        	    	    FB.setAccessToken(token);
        	    	    FB.getUser();
        	    	    sendResponse({});
        	    	    /* Check as soon as authorized */
        	    	    updateFacebook(true);

        	    	} catch(e) {
        	    	   if(sendResponse) { sendResponse({}); }
        	           Cache.set('deniedPermissions', 1);
        	           FB.setAccessToken(false);
        	    	}
    		    }
    		});
        </script>
        <script type="text/javascript" src="http://secure.gaug.es/track.js" data-site-id="4efe2668f5a1f5158a00000a" async="true" id="gauges-tracker"></script>
    </body>
</html>